package com.mayx.datax.output;

import cn.hutool.json.JSONUtil;
import com.mayx.datax.beans.Table;
import com.mayx.datax.configuration.Configuration;
import com.mayx.datax.helper.DataxJsonHelper;
import com.mayx.datax.helper.MysqlHelper;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;

/**
 * @description: 将HDFS的数据写到其他数据库的配置类
 * @author: mayx
 * @create: 2023-05-11 17:56
 **/
public class FromHDFS {
    public static void HDFSToMysql() throws IOException {
        // 生成 HDFS 出方向配置文件
        if (Configuration.EXPORT_OUT_DIR != null &&
                !"".equals(Configuration.EXPORT_OUT_DIR)) {
            MysqlHelper mysqlHelper = new MysqlHelper(
                    Configuration.MYSQL_URL_EXPORT,
                    Configuration.MYSQL_DATABASE_EXPORT,
                    Configuration.MYSQL_TABLES_EXPORT);
            DataxJsonHelper dataxJsonHelper = new DataxJsonHelper();

            // 获取迁移操作类型
            String migrationType = Configuration.EXPORT_MIGRATION_TYPE;

            // 创建父文件夹
            Files.createDirectories(Paths.get(Configuration.EXPORT_OUT_DIR));
            List<Table> tables = mysqlHelper.getTables();

            if (Configuration.IS_SEPERATED_TABLES.equals("1")) {
                for (int i = 0; i < tables.size(); i++) {
                    Table table = tables.get(i);
                    dataxJsonHelper.setTable(table, i, migrationType);
                }
                dataxJsonHelper.setColumns(tables.get(0), migrationType);

                // 输出最终Json配置
                FileWriter outputWriter = new FileWriter(Configuration.EXPORT_OUT_DIR + "/" + Configuration.MYSQL_DATABASE_EXPORT + "." + tables.get(0).name() + ".json");
                // 格式化JSON字符串
                String jsonStr = JSONUtil.toJsonStr(dataxJsonHelper.getOutputConfig(), 4);
                // 创建输出流，将其与File对象关联
                BufferedWriter bufferedWriter = new BufferedWriter(outputWriter);
                // 将格式化后的JSON字符串写入输出流中
                bufferedWriter.write(jsonStr);
                bufferedWriter.close();
                outputWriter.close();
            }

            for (Table table : tables) {
                // 设置表信息
                dataxJsonHelper.setTableAndColumns(table, 0, migrationType);
                // 输出最终Json配置
                FileWriter outputWriter = new FileWriter(Configuration.EXPORT_OUT_DIR + "/" + Configuration.MYSQL_DATABASE_EXPORT + "." + table.name() + ".json");
                // 格式化JSON字符串
                String jsonStr = JSONUtil.toJsonStr(dataxJsonHelper.getOutputConfig(), 4);
                // 创建输出流，将其与File对象关联
                BufferedWriter bufferedWriter = new BufferedWriter(outputWriter);
                // 将格式化后的JSON字符串写入输出流中
                bufferedWriter.write(jsonStr);
                bufferedWriter.close();
                outputWriter.close();
            }
        }
    }
}
